package com.jingnen.guess_index_server.service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Optional;

import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import com.jingnen.guess_index_server.entity.User;
import com.jingnen.guess_index_server.exception.UserNameExistsException;
import com.jingnen.guess_index_server.repository.UserRepository;

import jakarta.transaction.Transactional;

@Service
public class UserService {
    
    private UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public Optional<User> getUserByWxid(String wxid) {
        return userRepository.findByWxid(wxid);
    }

    public Optional<User> getUserByPhoneNumber(String phoneNumber) {
        return userRepository.findByPhoneNumber(phoneNumber);
    }

    public Optional<User> getUserByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    public User createUser(String wxid, String nickname, String avatar) {
        User user = new User();
        user.setWxid(wxid);
        user.setNickname(nickname);
        user.setAvatar(avatar);
        user.setCurrentCoin(0);
        user.setCurrentCash(new BigDecimal("0.00"));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        return userRepository.save(user);
    }

    @Transactional
    public User register(String userName, String password) {
        if (userRepository.existsByUserName(userName)) {
            throw new UserNameExistsException(userName);
        }

        User user = new User();
        user.setUserName(userName);
        user.setPassword(encodePassword(password));
        user.setCreateTime(LocalDateTime.now());

        return userRepository.save(user);
    }

    private String encodePassword(String raw) {
        return BCrypt.hashpw(raw, BCrypt.gensalt());
    }
}
